const Router = require('koa-router')
const router = new Router()
const callCloudDB = require('../utils/callCloudDB.js')
const cloudStorage = require('../utils/callCloudStorage.js')

router.get('/list', async (ctx, next) => {
    const params = ctx.request.query
    const query = `
        db.collection('videolist').skip(${params.start}).limit(${params.count}).orderBy('createTime','desc').get()
    `
    const res = await callCloudDB(ctx, 'databasequery',query)
    // console.log(res)

    //文件下载链接
    let fileList = []
    const data = res.data
    for (let i = 0, len = data.length; i < len; i++) {
        fileList.push({
            fileid: JSON.parse(data[i]).video,
            max_age: 7200
        })
    }
    const dlRes = await cloudStorage.download(ctx, fileList)
    // console.log(dlRes)
    let returnData = []
    for (let i = 0, len = dlRes.file_list.length; i < len; i++) {
        returnData.push({
            download_url:  dlRes.file_list[i].download_url,
            _id: JSON.parse(data[i])._id,
            _openid: JSON.parse(data[i])._openid,
            avatarUrl: JSON.parse(data[i]).avatarUrl,
            content: JSON.parse(data[i]).content,
            createTime: JSON.parse(data[i]).createTime,
            nickName: JSON.parse(data[i]).nickName,
            video: JSON.parse(data[i]).video
        })
    }
    // console.log(returnData)
    
    ctx.body = {
        data:returnData,
        code: 20000,
    }
})

router.post('/del',async(ctx,next) =>{
    const params = ctx.request.body
    // console.log(params)
    // 删除videolist
    const queryBlog = `db.collection('videolist').doc('${params._id}').remove()`
    const delBlogRes = await callCloudDB(ctx, 'databasedelete', queryBlog)
    
    // 删除video-comment
    const queryComment = `db.collection('video-comment').where({
        videoListId: '${params._id}'
    }).remove()`
    const delCommentRes = await callCloudDB(ctx, 'databasedelete', queryComment)
    
    // 删除云储存视频
    const delStorageRes = await cloudStorage.delete(ctx, params.video)
    ctx.body = {
        code: 20000,
        data: {
            delBlogRes,
            delCommentRes,
            delStorageRes
        }
    }
})

module.exports = router